package com.growthsee.rider.wrapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.growthsee.common.utils.SecurityUtils;
import com.growthsee.rider.domain.RiderAttachment;
import com.growthsee.rider.domain.RiderCourse;
import com.growthsee.rider.domain.RiderCourseCategory;
import com.growthsee.rider.domain.RiderQuestion;
import com.growthsee.rider.domain.dto.RiderCourseDto;
import com.growthsee.rider.domain.dto.RiderQuestionDto;
import com.growthsee.rider.enumeration.CourseTypeEnum;
import com.growthsee.rider.enumeration.YesNoEnum;
import com.growthsee.rider.mapper.RiderCourseMapper;
import com.growthsee.rider.service.RiderAttachmentService;
import com.growthsee.rider.service.RiderCourseCategoryService;
import com.growthsee.rider.service.RiderQuestionService;
import com.growthsee.rider.utils.ApplicationContexts;
import com.growthsee.rider.utils.BasicPathUtil;
import com.growthsee.rider.utils.BeanUtilsExt;
import com.growthsee.rider.utils.EmojiCharacterUtil;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ycj
 * @Description: 评价活动视图包装类
 * @date 2020/05/24
 **/
public class CourseWrapper {


    public static CourseWrapper builder() {
        return new CourseWrapper();
    }



    public String check(RiderCourse riderCourse){
        RiderCourseMapper riderCourseMapper = ApplicationContexts.getBean(RiderCourseMapper.class);
        LambdaQueryWrapper<RiderCourse> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RiderCourse::getDeleted, YesNoEnum.NO.getValue());
        if(StringUtils.isNotEmpty(riderCourse.getName())){
            queryWrapper.eq(RiderCourse::getName,riderCourse.getName());
        }
        if(StringUtils.isNotEmpty(riderCourse.getId())){
            queryWrapper.ne(RiderCourse::getId,riderCourse.getId());
        }
        Integer integer = riderCourseMapper.selectCount(queryWrapper);
        if(integer>0){
            return "课程已存在";
        }else return "";
    }


    public void emoji2Str(RiderCourseDto riderCourse) {
        if(StringUtils.isNotEmpty(riderCourse.getCourseExtend().getContent())){
            String content = riderCourse.getCourseExtend().getContent();
            content = content.replaceAll(BasicPathUtil.getCloudurl(), "");
            content=EmojiCharacterUtil.escape(content);
            riderCourse.getCourseExtend().setContent(content);
        }


    }

    public void str2emoji(RiderCourseDto riderCourse) {
        if(StringUtils.isNotEmpty(riderCourse.getCourseExtend().getContent())){
            String content = riderCourse.getCourseExtend().getContent();
            content = content.replaceAll("src=\"", "src=\""+BasicPathUtil.getCloudurl());
            content = EmojiCharacterUtil.reverse(content);
            riderCourse.getCourseExtend().setContent(content);
        }
    }

    /**
     * 配置试题
     * @param riderCourseDto
     */
    public String huildQuestion(RiderCourseDto riderCourseDto) {
        RiderQuestionService riderQuestionService = ApplicationContexts.getBean(RiderQuestionService.class);
        List<RiderQuestion>questions =riderQuestionService.list(Wrappers.<RiderQuestion>lambdaQuery()
                .eq(RiderQuestion::getCourseId,riderCourseDto.getId())
                .eq(RiderQuestion::getDeleted,YesNoEnum.NO.getValue())
                .orderByDesc(RiderQuestion::getCreateTime)
        );
        if(CollectionUtils.isNotEmpty(questions)){
            List<RiderQuestionDto>questionDtos=BeanUtilsExt.copyList(questions, RiderQuestionDto.class);
            //入职考题只返回通关试题数量
            if(CollectionUtils.isNotEmpty(questionDtos) && riderCourseDto.getType()== CourseTypeEnum.PAPER.getValue()){
                Collections.shuffle(questionDtos);
                questionDtos = questionDtos.stream().limit(riderCourseDto.getPassScore().intValue()).collect(Collectors.toList());
            }
            QuestionWrapper.builder().propertiesHandler(questionDtos);
            riderCourseDto.setQuestionDtos(questionDtos);
            if(ObjectUtils.isEmpty(riderCourseDto.getPassScore()) || riderCourseDto.getPassScore().compareTo(BigDecimal.ZERO)==0){
                riderCourseDto.setPassScore(new BigDecimal(questions.size()));
            }

        }
        return "";
    }

    /**
     * 处理课程基本信息
     * @param records
     */
    public void dataHandler(List<RiderCourseDto> records) {
        if(CollectionUtils.isNotEmpty(records)){
            List<String>categoryIds = records.stream().map(s->s.getCategoryId()).distinct().collect(Collectors.toList());
            RiderCourseCategoryService courseCategoryService = ApplicationContexts.getBean(RiderCourseCategoryService.class);
            List<RiderCourseCategory> list = courseCategoryService.list(Wrappers.<RiderCourseCategory>lambdaQuery().in(RiderCourseCategory::getId, categoryIds));
            RiderAttachmentService riderAttachmentService = ApplicationContexts.getBean(RiderAttachmentService.class);
            List<String> ids =  records.stream().map(s->s.getId()).distinct().collect(Collectors.toList());
            List<RiderAttachment> riderAttachments = riderAttachmentService.list(Wrappers.<RiderAttachment>lambdaQuery().in(RiderAttachment::getBusinessId, ids));
            records.forEach(v->{
                RiderCourseCategory courseCategory = list.stream().filter(s->StringUtils.equals(s.getId(),v.getCategoryId())).findFirst().orElse(null);
                if(ObjectUtils.isNotEmpty(courseCategory)){
                    v.setCategoryName(courseCategory.getName());
                }
                List<RiderAttachment> collect = riderAttachments.stream().filter(s -> StringUtils.equals(s.getBusinessId(), v.getId())).collect(Collectors.toList());
                v.setRiderAttachment(collect);
            });
        }
    }

    /**
     * 处理附件
     * @param riderCourse
     */
    public void riderAttachmentHandler(RiderCourseDto riderCourse) {
        RiderAttachmentService riderAttachmentService = ApplicationContexts.getBean(RiderAttachmentService.class);
        riderAttachmentService.remove(Wrappers.<RiderAttachment>lambdaQuery().eq(RiderAttachment::getBusinessId,riderCourse.getId()));
        if(CollectionUtils.isNotEmpty(riderCourse.getRiderAttachment())){
            riderCourse.getRiderAttachment().forEach(v->{
                v.setBusinessId(riderCourse.getId());
                v.setCreateTime(new Date());
                v.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
            });
            riderAttachmentService.saveBatch(riderCourse.getRiderAttachment());

        }
    }
}
